import 'package:flutter/material.dart';

import 'ly_dash_line.dart';

class LYDraggableView extends StatefulWidget {
  final double minH;
  const LYDraggableView({super.key, this.minH = 300});

  @override
  State<LYDraggableView> createState() => _LYDraggableViewState();
}

class _LYDraggableViewState extends State<LYDraggableView> {
  Offset updateMoveOffset = Offset.zero;
  Offset startMoveOffset = Offset.zero;
  Offset endMoveOffset = Offset.zero;

  double minH = 0;
  double minW = 0;
  double _dynamicW = 0;
  double _dynamicH = 0;
  double _rotation = 0;
  double _scale = 1;

  bool isMoving = false;

  @override
  void initState() {
    super.initState();
    minH = widget.minH;
    minW = minH * (9.0 / 16.0);
    _dynamicW = minW;
    _dynamicH = minH;
  }

  @override
  Widget build(BuildContext context) {
    // final view = View.of(context);
    // final size = view.physicalSize / view.devicePixelRatio;
    return Stack(
      fit: StackFit.expand,
      children: [
        Positioned(
            top: 0,
            left: 0,
            right: 0,
            height: 500,
            child: Container(
              width: double.infinity,
              height: 500,
              decoration: const BoxDecoration(
                color: Colors.blue,
              ),
              clipBehavior: Clip.hardEdge,
              child: Transform.scale(
                scale: _scale,
                child: Transform.rotate(
                  angle: _rotation,
                  child: Transform.translate(
                      offset: updateMoveOffset,
                      // transform: Matrix4.translationValues(
                      //     updateMoveOffset.dx, updateMoveOffset.dy, 0.0),
                      child: GestureDetector(
                        behavior: HitTestBehavior.deferToChild,
                        child: Container(
                          alignment: Alignment.center,
                          child: _makeContent(),
                        ), // 需要移动的组件
                        // onPanStart: (details) {
                        //   startMoveOffset = details.localPosition;
                        // },
                        // onPanUpdate: (details) {
                        //   Offset intervalOffset = details.localPosition -
                        //       startMoveOffset +
                        //       endMoveOffset;
                        //   setState(() {
                        //     updateMoveOffset = intervalOffset; // 更新坐标
                        //   });
                        // },
                        // onPanEnd: (details) {
                        //   endMoveOffset = updateMoveOffset;
                        // },
                        // onTapDown: (detail) {
                        // },
                        onScaleStart: (details) {
                          debugPrint("onScaleStart--${details.toString()}\n");
                          startMoveOffset = details.localFocalPoint;
                          isMoving = true;
                        },
                        onScaleEnd: (details) {
                          debugPrint("onScaleEnd--${details.toString()}\n");
                          debugPrint(
                              "onScaleEnd--${endMoveOffset.toString()}\n");
                          endMoveOffset = updateMoveOffset;
                          isMoving = false;
                        },
                        onScaleUpdate: (details) {
                          if (details.pointerCount == 1) {
                            Offset intervalOffset = details.localFocalPoint -
                                startMoveOffset +
                                endMoveOffset;
                            debugPrint("${intervalOffset.toString()}\n");

                            if (intervalOffset.dx < 20 &&
                                intervalOffset.dx > -20) {
                              intervalOffset = Offset(0, intervalOffset.dy);
                            }
                            if (intervalOffset.dy < 20 &&
                                intervalOffset.dy > -20) {
                              intervalOffset = Offset(intervalOffset.dx, 0);
                            }
                            setState(() {
                              updateMoveOffset = intervalOffset; // 更新坐标
                            });
                          } else if (details.pointerCount == 2) {
                            _rotation = details.rotation;
                            if (_rotation > -0.1 && _rotation < 0.1) {
                              _rotation = 0;
                            }
                            _scale = details.scale;
                            debugPrint("$_rotation");
                            setState(() {});
                            // double w = _dynamicW + 10 * details.scale.clamp(0.3, 1.8);
                            // _dynamicW = w;
                            // _dynamicH = w * (16.0 / 9.0);
                            // setState(() {});
                            //
                            // refreshW(-details.scale);
                            // refreshH(-details.scale * (16.0 / 9.0));
                          }
                        },
                      )),
                ),
              ),
            )),
        Positioned(
            height: 500,
            top: 0,
            left: 0,
            right: 0,
            child: IgnorePointer(
              child: Visibility(
                visible: isMoving,
                child: LYDashLine(
                  // width: size.width,
                  // height: 500,
                  axis: Axis.vertical,
                  lineColor: (Color.fromRGBO(
                      0,
                      0,
                      0,
                      (updateMoveOffset.dx < 30 && updateMoveOffset.dx > -30)
                          ? (1 - updateMoveOffset.dx.abs() / 30)
                          : 0)),
                ),
              ),
            )),
        Positioned(
            height: 500,
            top: 0,
            left: 0,
            right: 0,
            child: IgnorePointer(
              child: Visibility(
                visible: isMoving,
                child: LYDashLine(
                  // width: size.width,
                  // height: 500,
                  axis: Axis.horizontal,
                  lineColor: Color.fromRGBO(
                      0,
                      0,
                      0,
                      (updateMoveOffset.dy < 30 && updateMoveOffset.dy > -30)
                          ? (1 - updateMoveOffset.dy.abs() / 30)
                          : 0),
                ),
              ),
            )),
      ],
    );
  }

  double _dynamicSW = 0;
  double _dynamicSH = 0;

  Offset _panStartOffset = Offset.zero;
  Offset _panUpdateOffset = Offset.zero;
  Offset _panIntervalOffset = Offset.zero;

  Widget _makeContent() {
    return Container(
      width: _dynamicW <= 0 ? 10 : _dynamicW,
      height: _dynamicH <= 0 ? 10 : _dynamicH,
      color: Colors.red,
      child: Stack(
          clipBehavior: Clip.none,
          alignment: Alignment.center,
          children: [
            Positioned(
              left: 0,
              top: 0,
              child: GestureDetector(
                  onTap: () {
                    // 删除当前激活图标
                    // logic.onDeleteActiveFigure(_activeId!);
                  },
                  child: Container(
                    width: 24,
                    height: 24,
                    child: Icon(Icons.close),
                  )),
            ),
            Positioned(
              right: 0,
              bottom: 0,
              child: panResizeSquare(Alignment.bottomRight),
            ),
            Positioned(
              left: 0,
              bottom: 0,
              child: rotateResize(),
            ),
          ]),
    );
  }

  Widget rotateResize() {
    return GestureDetector(
        onTap: () {
          // 删除当前激活图标
          // logic.onDeleteActiveFigure(_activeId!);
        },
        onPanStart: (details) {},
        onPanUpdate: (details) {
          debugPrint(details.toString());
        },
        child: Container(
          width: 24,
          height: 24,
          child: Icon(Icons.rotate_left_sharp),
        ));
  }

  panResizeSquare(Alignment dir) {
    return GestureDetector(
        onPanStart: (details) {
          // 激活图标
          // logic.activeFigureId.value = _activeId!;
          _panStartOffset = details.localPosition;
          _dynamicSW = _dynamicW;
          _dynamicSH = _dynamicH;
        },
        onPanUpdate: (details) {
          // 激活图标
          // logic.activeFigureId.value = _activeId!;
          _panUpdateOffset = details.localPosition;
          debugPrint("---------$_panUpdateOffset--------------");

          double dx = _panUpdateOffset.dx - _panStartOffset.dx;
          double dy = _panUpdateOffset.dy - _panStartOffset.dy;

          _panIntervalOffset = -_panUpdateOffset + _panStartOffset;

          refreshW(_panIntervalOffset.dx);
          refreshH(_panIntervalOffset.dx * (16.0 / 9.0));
          return;
        },
        onPanEnd: ((details) {
          trLastH = trH;
          trLastW = trW;
        }),
        // 放大缩小图标
        onTap: () {},
        child: Offstage(
          offstage: false,
          child: Container(
            width: 24,
            height: 24,
            child: Icon(Icons.edit),
          ),
        ));
  }

  double trW = 0;
  double trLastW = 0;

  double trH = 0;
  double trLastH = 0;

  refreshW(double dx) {
    if (_dynamicW < minW && _panIntervalOffset.dx > 0) {
      _dynamicW = minW;
    }
    _dynamicW = _dynamicSW - dx < minW ? minW : _dynamicSW - dx;
    setState(() {});
  }

  refreshH(double dy) {
    if (_dynamicH < minH && _panIntervalOffset.dy > 0) {
      _dynamicH = minH;
    }
    _dynamicH = _dynamicSH - dy < minH ? minH : _dynamicSH - dy;
    setState(() {});
  }
}
